import React, {createElement} from "react";
import MenuConfig from '../../config'
import * as Icon from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { selectMenuList } from "../../store/reducers/tab";

import { Layout, Menu, Button, theme } from "antd";

const { Header, Sider, Content } = Layout;

// 动态获取icon
const iconToElement = (name) => createElement(Icon[name])

// 处理菜单数据
const items = MenuConfig.map((icon) => {
    // 没有子菜单
    const child = {
        key: icon.path,
        icon: iconToElement(icon.icon),
        label: icon.label
    }
    // 有子菜单
    if (icon.children) {
        child.children = icon.children.map((item) => {
            return {
                key: item.path,
                label: item.label
            }
        })
    }
    return child
})

const CommonAside = ({ collapsed }) => {
    const navigate = useNavigate()
    const dispatch = useDispatch()

    // 添加数据到store
    const setTabsList = (val) => {
        dispatch(selectMenuList(val))
    }

    // 点击菜单事件
    const selectManu = (e) => {
        console.log(e)
        let data
        MenuConfig.forEach(item => {
            if(item.path === e.keyPath[e.keyPath.length - 1]) {
                data = item
                // 如果有二级菜单
                if(e.keyPath.length > 1){
                    data = item.children.find(child => {
                        return child.path === e.key
                    })
                }
            }
        })
        setTabsList({
            path: data.path,
            name: data.name,
            label: data.label
        })
        navigate(e.key)
    }
    return (
        <Sider trigger={null} collapsed={collapsed}>
            <h3 className="app-name">{ collapsed ? 'PT' : 'PT种子站'}</h3>
            <Menu
                theme="dark"
                mode="inline"
                defaultSelectedKeys={["1"]}
                items={items}
                style={{
                    height: '100%'
                }}
                onClick={selectManu}
            />
        </Sider>
    )
 }

 export default CommonAside;